
app.factory('geolocation', ['$q', '$rootScope', '$window', function ($q, $rootScope, $window) {
    var PositionWrapper = function (position) {
        this.timestamp = position.timestamp;
        this.coords = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            accuracy: position.coords.accuracy,
            altitude: position.coords.altitude,
            altitudeAccuracy: position.coords.altitudeAccuracy,
            heading: position.coords.heading,
            speed: position.coords.speed
        };
    };

    return {
        getLocation: function (options) {
            options = options || {
                enableHighAccuracy: false,
                timeout: Infinity,
                maximumAge: 0
            };
            var deferred = $q.defer();
            if (!$window.navigator) {
                $rootScope.$apply(function () {
                    deferred.reject(new Error("Geolocation is not supported"));
                });
            }
            else {
                $rootScope.$emit("startGetCurrentPosition");
                $window.navigator.geolocation.getCurrentPosition(function (position) {
                    $rootScope.$emit("endGetCurrentPosition");
                    $rootScope.$apply(function () {
                        deferred.resolve(new PositionWrapper(position));
                    });
                }, function (error) {
                    $rootScope.$emit("endGetCurrentPosition");
                    $rootScope.$apply(function () {
                        deferred.reject(error);
                    });
                },
                options);
            }

            return deferred.promise;
        }
    };
} ]);